package com.bitbank.smartdevice.ui.home

import android.content.*
import android.net.wifi.WifiManager
import android.os.Build
import android.provider.Settings
import android.text.TextUtils
import android.view.View
import com.bitbank.smartdevice.R
import com.bitbank.smartdevice.ui.base.BaseFragment
import com.qmuiteam.qmui.widget.dialog.QMUIDialog
import com.tuya.smart.android.common.utils.NetworkUtil
import com.tuya.smart.android.device.utils.WiFiUtil
import kotlinx.android.synthetic.main.fragment_ec.*
import kotlinx.android.synthetic.main.fragment_ec.view.*


/**
 *  Date：2018/12/22
 *  Author：xulee
 *  Desc：对应DEMO 中的ECActivity, 输入Wifi密码
 */
@Suppress("NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS")
class ECFragment : BaseFragment() {

    override fun getLayoutID(): Int = R.layout.fragment_ec

    override fun initView(v: View) {
        registerWifiReceiver()
        v.topBar.addLeftBackImageButton().setOnClickListener { popBackStack() }
        v.topBar.setTitle(R.string.add_device)
        v.tvWifiName.text = WiFiUtil.getCurrentSSID(context)

        v.btnNext.setOnClickListener {
            goNextStep()
        }
    }

    private val mBroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(c: Context, intent: Intent) {
            if (intent.action == WifiManager.NETWORK_STATE_CHANGED_ACTION) {
                checkWifiNetworkStatus()
            }
        }
    }

    private fun setWifiSSID(ssid: String) {
        tvWifiName.text = ssid
    }

    private fun set5gVisiable(isShow: Boolean) {
        tip5g.visibility = if (isShow) View.VISIBLE else View.GONE
    }

    fun checkWifiNetworkStatus() {
        if (NetworkUtil.isNetworkAvailable(activity)) {
            val currentSSID = WiFiUtil.getCurrentSSID(activity)
            if (!TextUtils.isEmpty(currentSSID)) {
                setWifiSSID(currentSSID)
                set5gVisiable(is5GHz(currentSSID, context!!))
            }
            return
        }
//        mView.showNoWifi()
        toast("Wifi未连接~!!")
    }

    private fun is5GHz(ssid: String, context: Context): Boolean {
        val wifiManger = context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
        val wifiInfo = wifiManger.connectionInfo
        return if (wifiInfo != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            val freq = wifiInfo.frequency
            freq in 4901..5899
        } else
            ssid.toUpperCase().endsWith("5G")
    }

    fun goNextStep() {
        val passWord = etWifiPassword.text.toString()
        val ssid = WiFiUtil.getCurrentSSID(activity)
        if (!NetworkUtil.isNetworkAvailable(activity) || TextUtils.isEmpty(ssid)) {
            toast(R.string.connect_phone_to_network)
        } else {
            //对密码进行加密处理

            if (!is5GHz(ssid, activity!!)) {
                gotoBindDeviceActivity(ssid, passWord)
            } else {
                QMUIDialog.MessageDialogBuilder(activity)
                    .setMessage(R.string.ez_notSupport_5G_tip)
                    .addAction(R.string.ez_notSupport_5G_continue) { dialog, index ->
                        dialog.dismiss()
                        gotoBindDeviceActivity(ssid, passWord)
                    }
                    .addAction(R.string.ez_notSupport_5G_change) { dialog, index ->
                        dialog.dismiss()
                        userOtherWifi()
                    }
                    .create().show()
            }
        }
    }

    fun userOtherWifi() {
        var wifiSettingsIntent = Intent("android.settings.WIFI_SETTINGS")
        if (null != wifiSettingsIntent.resolveActivity(activity?.packageManager)) {
            activity?.startActivity(wifiSettingsIntent)
        } else {
            wifiSettingsIntent = Intent(Settings.ACTION_WIFI_SETTINGS)
            if (null != wifiSettingsIntent.resolveActivity(activity?.packageManager)) {
                activity?.startActivity(wifiSettingsIntent)
            }
        }
    }

    private fun gotoBindDeviceActivity(ssid: String, passWord: String) {

//        val intent = Intent(mActivity, ECBindActivity::class.java)
//        intent.putExtra(ECActivity.CONFIG_PASSWORD, passWord)
//        intent.putExtra(ECActivity.CONFIG_SSID, ssid)
//        intent.putExtra(ECActivity.CONFIG_MODE, mMode)
//        ActivityUtils.startActivity(mActivity, intent, ActivityUtils.ANIMATE_FORWARD, true)
    }

    private fun registerWifiReceiver() {
        try {
            activity?.registerReceiver(
                mBroadcastReceiver, IntentFilter(
                    WifiManager.NETWORK_STATE_CHANGED_ACTION
                )
            )
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private fun unRegisterWifiReceiver() {
        try {
            activity?.unregisterReceiver(mBroadcastReceiver)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        unRegisterWifiReceiver()
    }

//    override fun onFetchTransitionConfig(): QMUIFragment.TransitionConfig {
//        return QMUIFragment.SCALE_TRANSITION_CONFIG
//    }

}